<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="70px">
            <el-form-item label="项目名称" prop="projectName">
                <el-row :gutter="10">
                    <el-col :span="18">
                        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称进行搜索" clearable
                            @keyup.enter="handleQuery" />
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" icon="Search" @click="handleQuery" block>搜索</el-button>
                    </el-col>
                </el-row>
            </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="projectList" border>
            <el-table-column label="项目名称" show-overflow-tooltip width="220" align="center" prop="projectName" />
            <el-table-column label="阶段" align="center" show-overflow-tooltip width="100" prop="phaseName" />
            <el-table-column label="发起人" align="center" show-overflow-tooltip width="80" prop="createUserName" />
            <el-table-column label="预计验收日期" align="center" prop="acceptTime" width="120" show-overflow-tooltip>
                <template #default="scope">
                    <span>{{ parseTime(scope.row.acceptTime, "{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="客户名称" align="center" show-overflow-tooltip width="220" prop="customerName" />
            <el-table-column label="管家婆项目" align="center" prop="housekeeperName" show-overflow-tooltip width="300" />

            <!-- 固定操作列 -->
            <el-table-column label="操作" fixed="right" width="80" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" @click="handleUpdate(scope.row)">添加</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />


        <!-- 添加或修改绩效基本信息对话框 -->

        <el-dialog @close="cancel" fullscreen v-model="open" width="10%" append-to-body>
            <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="项目信息" name="first">

                    <el-descriptions class="margin-top" size="small" border>
                        <el-descriptions-item>
                            <template #label>
                                <div class="cell-item">
                                    项目
                                </div>
                            </template>
                            {{ form.projectName }}
                        </el-descriptions-item>
                    </el-descriptions>
                    <el-divider style="font-size: 16px; font-weight: bold;">附件信息</el-divider>
                    <el-button :disabled="!addFilePer" type="primary" plain :icon="Plus" @click="addFiles()"
                        style="margin-bottom: 10px;">添加附件</el-button>
                    <el-table v-loading="loading" :data="attachmentList" border
                        @selection-change="handleSelectionChange">
                        <el-table-column label="附件类别" align="center" prop="attachmentType">
                            <template #default="scope">
                                <dict-tag :options="file_type" :value="scope.row.attachmentType" />
                            </template>
                        </el-table-column>
                        <el-table-column label="附件标题" align="center" prop="attachmentTitle" />
                        <el-table-column label="附件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
                            <template #default="scope">
                                <el-link type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName
                                }}</el-link>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作员" align="center" prop="operator" />
                        <el-table-column label="操作时间" align="center" prop="startDate" width="180">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" fixed="right" width="100"
                            class-name="small-padding fixed-width">
                            <template #default="scope">
                                <el-button :disabled="!addFilePer" link type="primary"
                                    @click="handleUpdateFile(scope.row)">修改</el-button>
                                <el-button :disabled="!addFilePer" link type="primary"
                                    @click="handleDeleteFile(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
                    <div>
                        <el-divider style="font-size: 16px; font-weight: bold;">实施日志信息</el-divider>
                        <el-button :disabled="!(addImplementPer && rowPhaseId == '3')" type="primary" plain :icon="Plus"
                            @click="addImplements()" style="margin-bottom: 10px;">添加实施日志</el-button>
                        <el-table v-loading="loading" border :data="implementList"
                            @selection-change="handleSelectionChange">
                            <!-- <el-table-column label="关联的阶段id" align="center" prop="phaseId" /> -->
                            <el-table-column label="实施日期" align="center" prop="implementDate" width="120">
                                <template #default="scope">
                                    <span>{{ parseTime(scope.row.implementDate, '{y}-{m}-{d}') }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="附件照片" align="center" prop="images" width="100">
                                <template #default="scope">
                                    <image-preview :src="scope.row.images" v-if="scope.row.images" :width="50" :height="50" />
                                </template>
                            </el-table-column>
                            <el-table-column label="标题" align="center" prop="title" />
                            <el-table-column label="内容" align="center" prop="remark" />
                            <el-table-column label="文件类型" align="center" prop="fileType">
                                <template #default="scope">
                                    <dict-tag :options="log_type" :value="scope.row.fileType" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作人" align="center" prop="operator" />
                            <el-table-column label="操作时间" align="center" prop="startDate" width="180">
                                <template #default="scope">
                                    <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" align="center" fixed="right" width="100"
                                class-name="small-padding fixed-width">
                                <template #default="scope">
                                    <el-button link :disabled="!(addImplementPer && rowPhaseId == '3')" type="primary"
                                        @click="handleUpdateImplement(scope.row)">修改</el-button>
                                    <el-button link :disabled="!(addImplementPer && rowPhaseId == '3')" type="primary"
                                        @click="handleDeleteImplement(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <div class="dialog-footer">
                    <!-- <el-button v-if="manger" type="primary" @click="updateForm">修改项目信息</el-button>
                    <el-popconfirm v-if="status == 1 && haveNext" confirm-button-text="确认" cancel-button-text="取消"
                        title="确认提交到下一步?" @confirm="nextPhase">
                        <template #reference>
                            <el-button type="primary">下一步</el-button>
                        </template>
    </el-popconfirm> -->
                    <el-button type="primary" @click="cancel">关 闭</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 添加或修改附件对话框 -->
        <el-dialog title="附件信息" v-model="openFile" width="90%" append-to-body>
            <el-form ref="attachmentRef" :model="fileForm" size="large" :rules="fileRules" label-width="80px">
                <el-form-item label="附件类别" prop="attachmentType">
                    <el-select @change="setUploadType" v-model="fileForm.attachmentType" placeholder="请选择附件类别">
                        <el-option v-for="dict in file_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="附件标题" prop="attachmentTitle">
                    <el-input v-model="fileForm.attachmentTitle" placeholder="请输入附件标题" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="fileForm.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="上传附件" prop="filePath">
                    <file-upload :limit="1" :fileType="fileAccept" v-model="fileForm.filePath" />
                </el-form-item>
                <template v-if="fileForm.attachmentType == 5 || fileForm.attachmentType == 22"><el-tag type="primary"
                        style="margin-left: 10px;">提示：多次导入正式或结算清单或会以最后一份为准</el-tag></template>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="cancelFile">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog title="实施日志" v-model="openImplement" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="implementRef"  :model="implementForm" :rules="ImplementRules" label-width="80px">

        <el-form-item label="实施日期" prop="implementDate">
          <el-date-picker clearable v-model="implementForm.implementDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择实施日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input clearable v-model="implementForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="remark">
          <el-input clearable v-model="implementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="附件照片" prop="images">
          <image-upload v-model="implementForm.images" />
        </el-form-item>

        <el-form-item label="上传附件" prop="filePath">
          <file-upload v-model="implementForm.files" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitimplementForm">确 定</el-button>
          <el-button @click="canceImplement">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </div>
</template>

<script setup name="Project">
import {
    listProject,
    appListProject,
    getProject,
    updateProject,
    getCompanyList,
    getFinanceList,
    listParticipan, addParticipan, updateParticipan, getPermission,
    getStatus, saveUserTableConfig, getUserTableConfig,
    listImplement, getImplement, delImplement, addImplement, updateImplement, listPay
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/project/project";
import { listPhase, getPhase, delPhase, addPhase, updatePhase } from "@/api/project/project";
import {
    Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";

import { getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary, updateDictionary, listAllDictionary } from "@/api/project/dictionary";
const haveNext = ref(false)

import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();

const addPersonPer = ref(false)
const addFilePer = ref(false)
const addPayPer = ref(false)
const addImplementPer = ref(false)
const addWarrantyPer = ref(false)
const addAccounting = ref(false)
const manger = ref(false);//当前人员是否项目经理或销售负责人
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { log_type } = proxy.useDict('log_type');
const { company_type } = proxy.useDict("company_type");
const attachmentList = ref([]);
const implementList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const open = ref(false);
const isView = ref(false);
const openView = ref(false);
const openOper = ref(false);
const openFile = ref(false);
const openImplement = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const projectNo = ref("")
const contractAmount = ref(0)
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const haveImplement = ref(false);//是否有添加实施日志信息的权限
const haveAddPerson = ref(false);//是否有添加参与人员的权限
const status = ref("0");
const currenrPhaseId = ref()
const loadingQuery = ref(false)
const fileAccept = ref(["doc", "docx", "cad", "dwg","xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'],);
function setUploadType(selection) {
    console.log("选择的文件类型", selection);
    const temp = ["doc", "docx", "cad", "dwg","xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'];
    if (selection == 5 || selection == 22) {//正式清单 只允许上传excel
        fileAccept.value = ["xls", "xlsx"]
    } else {
        fileAccept.value = temp
    }
}

const activeName = ref('first')
function handleClick(item, event) {
    // activeName
    console.log("tabs页面跳转", item.paneName, event)
    activeName.value = item.paneName
}


import { ElLoading } from 'element-plus'
const formDisabled = ref(true);
import { ref } from "vue";
const data = reactive({
    currentProject: {},
    form: {
        createUserName: null,
        createUserId: null,
        createDeptName: null,
        createDept: null,
    },
    currentConfig: {//当前环节关联的配置表

    },
    personForm: {
    },
    fileForm: {

    },
    implementForm: {

    },

    queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectAmount: null,
        projectType: null,
        projectUnit: null,
        acceptTime: null,
        customerName: null,
        housekeeperName: null,
        phaseCode: null,
        minProjectAmount: null,
        maxProjectAmount: null
    },
    rules: {
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
        projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
    },
    personRules: {
        postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
        participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
    },

    fileRules: {
        attachmentType: [{ required: true, message: "请选择附件类型", trigger: "blur" }],
        filePath: [{ required: true, message: "请上传附件", trigger: "blur" }],
    },

    ImplementRules: {
        implementDate: [{ required: true, message: "请选择实施日期", trigger: "blur" }],
    }

});



async function downloadFile(row) {
    //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
    if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
        let params = {
            projectNo: row.projectNo,
            postIds: [2, 5,6,7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
        }
        const res = await getPermission(params).then((response) => {
            console.log("下载附件", response.data);
            return response.data
        });
        if (!res) {
            proxy.$modal.msgError("暂无权限下载此附件");
            return
        }
    }

    var name = row.fileName;
    var url = row.filePath || row.files;
    // var suffix = url.substring(url.lastIndexOf("."), url.length);
    const a = document.createElement('a')
    a.setAttribute('download', name)
    a.setAttribute('target', '_blank')
    a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
    a.click()
}


/** 修改按钮操作 */
function handleUpdateFile(row) {
    resetFile();
    const _attachmentId = row.attachmentId || ids.value
    getAttachment(_attachmentId).then(response => {
        fileForm.value = response.data;
        openFile.value = true;
    });
}
/** 修改付款信息按钮操作 */
function handleUpdateImplement(row) {
    resetImplement();
    const _Id = row.id || ids.value
    getImplement(_Id).then(response => {
        implementForm.value = response.data;
        openImplement.value = true;
    });
}

// 获取文件名称
function getFileName(name) {
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
    } else {
        return name;
    }
}

/** 提交按钮 */
function submitFileForm() {
    proxy.$refs["attachmentRef"].validate(valid => {
        if (valid) {

            // 定义 loading 实例变量
            let loadingInstance = null;
            if (fileForm.value.attachmentType == "5" || fileForm.value.attachmentType == "22") {
                //正数清单上传慢  加上loading
                loadingInstance = ElLoading.service({ fullscreen: true, text: '清单上传中...' });

            }


            fileForm.value.fileName = getFileName(fileForm.value.filePath)
            fileForm.value.projectNo = projectNo.value
            if (fileForm.value.attachmentId != null) {
                updateAttachment(fileForm.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    if (loadingInstance) {
                        loadingInstance.close();
                    }
                    openFile.value = false;
                    getListParticipan(projectNo.value)
                }).finally(() => {
                    loadingInstance.close();
                });
            } else {
                addAttachment(fileForm.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    if (loadingInstance) {
                        loadingInstance.close();
                    }
                    openFile.value = false;
                    getListParticipan(projectNo.value)
                }).finally(() => {
                    loadingInstance.close();
                });
            }
        }
    });
}
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

/** 提交按钮 */
function submitimplementForm() {
  proxy.$refs["implementRef"].validate(valid => {
    if (valid) {
      implementForm.value.projectNo = projectNo.value
      if(implementForm.value.files){
        implementForm.value.fileName = getFileName(implementForm.value.files)
      }
      if (implementForm.value.id != null) {
        updateImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addImplement(implementForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openImplement.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}



/** 删除按钮操作 */
function handleDeleteFile(row) {
    const _attachmentIds = row.attachmentId || ids.value;
    proxy.$modal.confirm('是否确认删除？').then(function () {
        return delAttachment(_attachmentIds);
    }).then(() => {
        getListParticipan(projectNo.value)
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}


function handleDeleteImplement(row) {
    const _Id = row.id
    proxy.$modal.confirm('是否确认删除？').then(function () {
        return delImplement(_Id);
    }).then(() => {
        getListParticipan(projectNo.value)
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}



//添加附件信息
function addFiles() {
    //重置表单
    resetFile()
    // personList.value = []
    openFile.value = true
    title.value = "添加附件信息";
    fileForm.value.phaseId = rowPhaseId.value
}
//添加实施日志信息 销售负责人添加实施日志信息？
function addImplements() {
    resetImplement()
    implementForm.value.totalAmount = contractAmount.value//合同签订金额自动带出
    implementForm.value.fileType = 0 //默认选择第一个
    // personList.value = []
    openImplement.value = true
    implementForm.value.phaseId = rowPhaseId.value
}


const { queryParams, form, rules, personForm, personRules, fileRules, ImplementRules, fileForm, implementForm, currentConfig } = toRefs(data);

function getCurrUser(id) {
    getPosts(id).then(response => {
        console.log("66666666", response);


    });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
    let params = {
        projectNo: projectNo.value,
        // phaseId: 2,//项目实施 写死
        postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    // haveImplement.value = await hasPermisson(params)
    haveAddPerson.value = await hasPermisson(params)
    console.log("添加信息", haveAddPerson.value);

}

//是否是财务
async function isFinance() {
    let params = {
        projectNo: projectNo.value,
        // phaseId: 2,//实施阶段 写死
        postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    finance.value = await hasPermisson(params)

    console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
    const res = await getPermission(params).then((response) => {
        console.log("权限信息", response.data);
        return response.data
    });
    return res
}



function initData() {
    getUser().then(response => {
        posts.value = response.posts;
        console.log("岗位信息", response);
    });
    listAllUser().then(res => {
        console.log("userlist", res);
        userList.value = res
    });

    getInfo().then((res) => {
        console.log("当前用户", res);
        getCurrUser(res.user.userId)
    })
        .catch((error) => {
            console.log("error", error);
        });
}


/** 查询绩效基本信息列表 */
function getList() {
    loading.value = true;
    queryParams.value.params = {};
    appListProject(queryParams.value).then((response) => {
        console.log("response", response);
        projectList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
        console.log('projectList', projectList);

    });
}

// 取消按钮
function cancel() {
    console.log("关闭");
    open.value = false;
    openView.value = false
    reset();

    //判断是否是数据看板过来的 是则跳回去
    if (isDataView.value) {
        router.push({
            path: '/project/dataView',
        });
    }

}
// 取消按钮
function cancelPerson() {
    openOper.value = false;
    resetPer();
}

// 取消按钮
function cancelFile() {
    openFile.value = false;
    resetFile();
}


// 取消按钮
function canceImplement() {
    openImplement.value = false;
    resetImplement();
}


//获取用户详细信息
function getUserInfo() {
    getInfo().then((res) => {
        const user = res.user;
        form.value.createUserName = user.nickName;
        form.value.createUserId = user.userId;
        form.value.createDeptName = user.dept.deptName
        form.value.createDept = user.deptId
        console.log("user", form);
    })
        .catch((error) => {
            console.log("error", error);
        });


    // listDictionary().then(response => {
    //   form.value.phaseName = response.data?.rows[0]?.phaseName
    //   form.value.phaseCode = response.data?.rows[0]?.phaseCode
    // });

}
// 表单重置 
function reset() {
    form.value = {
        projectNo: null,
        projectName: null,
        createDeptName: null,
        projectAmount: null,
        projectType: null,
        projectUnit: null,
        acceptTime: null,
        customerAddress: null,
        customerName: null,
        housekeeperProject: null,
        phaseCode: null,
        remark: null,
        minProjectAmount: null,
        maxProjectAmount: null,
        companyName: null,
        companyType: null,
        companyNo: null
    };
    proxy.resetForm("projectRef");

}


const setCompanyTypeName = (datas) => {
    //对应的名称
    const filteredObjects = company_type.value.filter((obj) => datas.includes(obj.value));
    form.value.companyName = '';
    const labels = filteredObjects.map((obj) => obj.label);
    form.value.companyName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};

// 表单重置
function resetPer() {
    personForm.value = {
        // projectNo: null,
        // projectName: null,
        // createDeptName: null,
        // projectAmount: null,
        // projectType: null,
        // projectUnit: null,
        // acceptTime: null,
        // customerAddress: null,
        // customerName: null,
        // housekeeperProject: null,
        // phaseCode: null,
        // remark: null,
        // minProjectAmount: null,
        // maxProjectAmount: null
    };
    proxy.resetForm("participanRef");

}

// 表单重置
function resetFile() {
    fileForm.value = {
        // projectNo: null,
        // projectName: null,
        // createDeptName: null,
        // projectAmount: null,
        // projectType: null,
        // projectUnit: null,
        // acceptTime: null,
        // customerAddress: null,
        // customerName: null,
        // housekeeperProject: null,
        // phaseCode: null,
        // remark: null,
        // minProjectAmount: null,
        // maxProjectAmount: null
    };
    proxy.resetForm("attachmentRef");

}

// 表单重置
function resetImplement() {
    implementForm.value = {
        // projectNo: null,
        // projectName: null,
        // createDeptName: null,
        // projectAmount: null,
        // projectType: null,
        // projectUnit: null,
        // acceptTime: null,
        // customerAddress: null,
        // customerName: null,
        // housekeeperProject: null,
        // phaseCode: null,
        // remark: null,
        // minProjectAmount: null,
        // maxProjectAmount: null
    };
    proxy.resetForm("implementRef");

}



/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}




/** 重置按钮操作 */
function resetQuery() {
    daterangeAcceptTime.value = [];
    proxy.resetForm("queryRef");
    queryParams.value.minProjectAmount = null
    queryParams.value.maxProjectAmount = null
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.projectNo);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

function setPostName(id) {
    // 筛选 posts.value 中符合条件的对象
    const filteredObjects = posts.value.filter((obj) => obj.postId === id);
    // 清空 projectTypeName 字段
    personForm.value.postName = '';
    console.log("postName", filteredObjects);
    personForm.value.postName = filteredObjects[0].postName
}

function setPersonName(id) {
    // 筛选 posts.value 中符合条件的对象
    const filteredObjects = userList.value.filter((obj) => obj.userId === id);
    // 清空 projectTypeName 字段
    personForm.value.participanName = '';
    console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

    personForm.value.participanName = filteredObjects[0]?.nickName
}


const rowPhaseId = ref("")
/** 添加立项前期信息 */
function handleUpdate(row) {
    rowPhaseId.value = row.phaseId
    console.log("rowPhaseId.value", rowPhaseId.value);

    activeName.value = "first"
    reset();
    isView.value = false
    const _projectNo = row.projectNo || ids.value;
    projectNo.value = row.projectNo //存放项目id
    contractAmount.value = row.contractAmount
    getProject(_projectNo).then((response) => {
        form.value = response.data;
        open.value = true;
        title.value = "修改项目基本信息";
    });
    isManger()
    getListParticipan(row.projectNo)

    getNextPer(row.projectNo);
}


function getListParticipan(projectNo) {
    console.log("projectNoprojectNo", projectNo);

    let params = {
        projectNo: projectNo
    }
    listParticipan(params).then((response) => {
        console.log("response", response);
        personList.value = response.data
    });

    listAttachment(params).then((response) => {
        attachmentList.value = response.data;
    });


    listImplement(params).then((response) => {
        implementList.value = response.data;
    });

    listPay(params).then((response) => {
        payList.value = response.data;
    });



    isFinance()
    isSale()

    getCurrPhase(projectNo)

}



async function nextPhase() {
    //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验
    if (form.value.acceptTime == null || form.value.acceptTime == '') {
        proxy.$modal.msgError("请填写预计验收日期");
        return
    }

    if (form.value.acceptTime < form.value.planDate) {
        proxy.$modal.msgError("预计验收日期不能早于预计开始日期");
        return
    }

    let params = {
        projectNo: projectNo.value,
        id: 3//项目实施
    }
    //校验该环节的所有配置
    const result = await getCheck(params).then(response => {//立项阶段 id写死
        console.log("项目实施校验", response);
        return response
    });
    if (result.data.permission == false) {
        proxy.$modal.msgError(result.data.message);
        return
    }
    //校验通过 更新当前阶段信息



    let updateParams = {
        id: currenrPhaseId.value,
    }
    const updateResult = await updatePhase(updateParams).then((response) => {
        console.log("更新阶段", response);
        return response
    });

    if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
        let addParams = {
            projectNo: projectNo.value,
            phaseId: 4,//项目验收
            remark: form.value.phaseRemark//留言
        }
        addPhase(addParams).then((response) => {

        })
    }

    proxy.$modal.msgSuccess("提交成功");
    status.value = 2
    open.value = false



    let currPhase = {
        projectNo: projectNo.value,
        phaseId: 3
    }
    getStatus(currPhase).then((response) => {
        console.log("当前阶段信息", response);
        if (response.data?.status && response.data?.status == '2') {//如果该环节已完成 跳转到下一个环节

            router.push({
                path: '/accept/projectAccept',
                query: { projectNo: projectNo.value }
            });

        }

        else {
            getList()
        }

    });

}


function getCurrPhase(projectNo) {//查询当前阶段有无完成
    let currPhase = {
        projectNo: projectNo,
        phaseId: 3//实施阶段 0
    }
    getStatus(currPhase).then((response) => {
        console.log("当前阶段信息", response);
        if (response.data == null) {
            //  currenrPhaseId.value = response.data.id
        } else {
            status.value = response.data.status
            currenrPhaseId.value = response.data.id
        }
    });
}


/** 提交按钮 */
function submitForm() {

    proxy.$refs["projectRef"].validate((valid) => {
        if (valid) {
            if (form.value.projectNo != null) {
                updateProject(form.value).then((response) => {
                });
            }
        }
    });
}

//是否是项目经理或销售负责人
async function isManger() {
    let params = {
        projectNo: projectNo.value,
        // phaseId: 1,//立项前期 写死
        postIds: [2, 5]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    manger.value = await hasPermisson(params)
    console.log("是否是项目经理或销售负责人ger.value", manger.value);
    formDisabled.value = !manger.value
}



function getCompanys() {
    getCompanyList(queryParams.value).then((response) => {
        companyList.value = response.data.map(item => ({
            ...item, // 保留原始属性
            value: item.id, // 添加 value 字段
            label: item.companyName, // 添加 label 字段
        }));
    });
    getFinanceList(queryParams.value).then((response) => {
        financeList.value = response.data.map(item => ({
            ...item, // 保留原始属性
            value: item.finance, // 添加 value 字段
            label: item.finance, // 添加 label 字段
        }));
    });
}


function getCurrPhaseConfig() {
    getDictionary(3).then(response => {//项目实施
        currentConfig.value = response.data;
    });
}

function getNextPer(projectNo) {
    let params = {
        projectNo: projectNo,
        id: 3//项目实施
    }
    getNextPermission(params).then(response => {//立项阶段 id写死
        console.log("实施 下一步权限", response);
        haveNext.value = response.data.permission

        addPersonPer.value = response.data.addPerson
        addFilePer.value = response.data.addFile
        addPayPer.value = response.data.addPay
        addImplementPer.value = response.data.addImplement
        addWarrantyPer.value = response.data.addWarranty
        addAccounting.value = response.data.addAccounting

    });
}

getCurrPhaseConfig()

getList();
getCompanys();
initData()

const isDataView = ref(false)
onMounted(() => {
    nextTick(() => {
        console.log("实施跳转", route.query);
        if (route.query?.projectNo) {
            //判断是不是从数据看板跳过来的 如果是 关闭页面的时候跳回去
            if (route.query?.type != undefined && route.query?.type != null && route.query?.type == 'dataView') {
                isDataView.value = true
            }

            getProject(route.query?.projectNo).then((response) => {
                form.value = response.data;
                handleUpdate(form.value)

                // 创建一个新的 query 对象，排除 projectNo
                const { projectNo, ...restQuery } = route.query;
                // 使用 replace 更新路由，不保留 projectNo
                router.replace({
                    path: route.path,
                    // query: restQuery
                });
            });
        }
    })

});



</script>